﻿/// <reference path="../_references.js" />
(function (e) {

    e.eventManager = function () {
        this.subs = {};
    };

    e.eventManager.prototype = {
        subscribe: function (eventName, callback, context) {
            if (!this.subs[eventName]) {
                this.subs[eventName] = [];
            }
            this.subs[eventName].push({
                context: context,
                callback: callback
            });
        },
        publish: function (eventName, data) {
            e.log("Publishing event: " + eventName);
            var self = this;
            if (self.subs[eventName]) {
                var i = 0;
                var id = setInterval(function () {
                    if (self.subs[eventName][i]) {
                        var context = self.subs[eventName][i].context || this;
                        try {
                            self.subs[eventName][i].callback.call(context, data);
                        }
                        catch (ex) {
                            e.log("Error while publishing event: " + eventName + " (" + ex + ")");
                        }
                        i++;
                    }
                    else {
                        clearInterval(id);
                    }
                }, 0);
            }
        },
        unsubscribe: function (eventName, context) {
            
        }
    };

} (this.eg = this.eg || {}));